<template>
  <MainLayout>
    <div class="guardpost-view">
      <div id="map-container"></div>
      <!-- 右侧信息面板 -->
      <div class="info-panel">
        <GuardPointsPanel />
      </div>
    </div>
  </MainLayout>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import MainLayout from "../main/components/MainLayout.vue";
import GuardPointsPanel from "../main/components/panels/GuardPointsPanel.vue";

// 地图实例
let map = null;

// 值守点数据
const guardList = ref([
  { id: 1, name: "石门隧道-北", position: [106.455, 29.575], status: "online" },
  { id: 2, name: "石门隧道-南", position: [106.445, 29.565], status: "online" },
  { id: 3, name: "朝阳隧道-东", position: [106.315, 29.525], status: "online" },
  { id: 4, name: "朝阳隧道-西", position: [106.305, 29.515], status: "offline" },
  { id: 5, name: "双福隧道-北", position: [106.285, 29.405], status: "online" },
  { id: 6, name: "双福隧道-南", position: [106.275, 29.395], status: "online" },
  { id: 7, name: "铜锣隧道-东", position: [106.155, 29.205], status: "online" },
  { id: 8, name: "铜锣隧道-西", position: [106.145, 29.195], status: "offline" },
]);

onMounted(() => {
  nextTick(() => {
    window.addEventListener("resize", handleResize);
  });
  // 将initMap方法暴露给window对象
  window.initMap = initMap;
  initMap();
});

// 初始化地图
function initMap() {
  // 如果地图已经存在，先销毁它
  if (map) {
    map.destroy();
    map = null;
  }

  // 设置安全配置
  window._AMapSecurityConfig = {
    securityJsCode: "2b71b40da1bbd37b27d45a76cb574923",
  };

  // 加载地图API
  AMapLoader.load({
    key: "dc4cd392c3fd43f5e675d2d51f4c612c", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Scale", "AMap.DistrictSearch", "AMap.DistrictLayer"], // 和隧道概况页面保持一致
  })
    .then((AMap) => {
      try {
        // 检查容器是否存在
        const container = document.getElementById("map-container");
        if (!container) {
          console.error("地图容器不存在");
          return;
        }

        // 创建地图实例
        map = new AMap.Map("map-container", {
          viewMode: "3D", // 是否为3D地图模式
          zoom: 8.0, 
          center: [107.8, 29.9], 
          pitch: 0, // 俯仰角度
          showBuildingBlock: false, // 不显示3D建筑物
          showLabel: true, // 显示标签
          mapStyle: "amap://styles/9fbf781893474ba556820c4b787efcf1" // 使用自定义地图样式ID
        });

        // 加载重庆行政区域边界
        const districtSearch = new AMap.DistrictSearch({
          level: "city", // 行政级别
          subdistrict: 0, // 不返回下级行政区
          extensions: "all", // 返回行政区边界坐标点
          showbiz: false // 不返回商圈
        });
        
        // 搜索重庆市行政区域
        districtSearch.search("重庆市", (status, result) => {
          if (status === "complete" && result.districtList && result.districtList.length > 0) {
            const boundaries = result.districtList[0].boundaries;
            
            if (boundaries) {
              // 绘制重庆边界
              const polygons = [];
              
              for (let i = 0; i < boundaries.length; i++) {
                // 创建重庆市区域多边形，降低填充透明度以显示内部路网
                const polygon = new AMap.Polygon({
                  path: boundaries[i],
                  strokeColor: "#3ec6ff", // 边界线颜色
                  strokeWeight: 2, // 边界线宽度
                  strokeOpacity: 1, // 边界线透明度
                  fillColor: "#012F66", // 填充颜色为深蓝色
                  fillOpacity: 0.4, // 降低填充透明度，让内部路网可见
                  zIndex: 10
                });
                polygons.push(polygon);
              }
              
              // 添加多边形到地图
              map.add(polygons);
              
              // 创建一个覆盖整个地图的蒙版，使重庆市以外的区域路网变暗
              const outerMask = new AMap.Polygon({
                path: [
                  [72, 54], // 中国左上角
                  [72, 4],  // 中国左下角
                  [138, 4], // 中国右下角
                  [138, 54] // 中国右上角
                ],
                strokeColor: "transparent", 
                strokeWeight: 0,
                fillColor: "#071a36", 
                fillOpacity: 0.6, // 半透明遮罩
                zIndex: 9, // 置于重庆边界下方
                bubble: true // 禁止冒泡，使得地图交互穿过这个图层
              });
              
              // 添加外部遮罩到地图
              map.add(outerMask);
              
              // 添加完边界后添加标记
              addGuardpostMarkers();
            } else {
              console.error("获取重庆市行政区域失败");
              // 即使获取失败也添加标记
              addGuardpostMarkers();
            }
          } else {
            console.error("获取重庆市行政区域失败");
            // 即使获取失败也添加标记
            addGuardpostMarkers();
          }
        });
      } catch (error) {
        console.error("地图初始化失败:", error);
      }
    })
    .catch((e) => {
      console.error("AMap加载失败:", e);
    });
}

// 添加值守点标记
function addGuardpostMarkers() {
  if (!map) return;
  
  guardList.value.forEach(guard => {
    const markerContent = `
      <div class="custom-marker ${guard.status}">
        <div class="marker-icon"></div>
        <div class="pulse-ring"></div>
      </div>
    `;
    
    const marker = new AMap.Marker({
      map: map,
      position: guard.position,
      content: markerContent,
      anchor: 'center',
      offset: new AMap.Pixel(0, 0),
      label: {
        content: guard.name,
        direction: 'top',
        offset: new AMap.Pixel(0, -8),
        style: {
          color: '#fff',
          fontSize: '12px',
          fontWeight: 'bold',
          backgroundColor: 'rgba(10,30,60,0.7)',
          border: guard.status === 'online' ? '1px solid #00c853' : '1px solid #ff5252',
          padding: '3px 6px',
          borderRadius: '3px'
        }
      }
    });
    
    // 添加点击事件
    marker.on('click', () => {
      map.setCenter(guard.position);
      map.setZoom(12);
    });
  });
}

// 监听窗口大小变化
function handleResize() {
  // 地图自适应大小
  map && map.resize();
}

// 创建高亮路网图层函数
function createHighlightedRoadLayer(boundaries) {
  // 添加路网高亮，使用自定义Canvas层
  const canvas = document.createElement('canvas');
  // 添加willReadFrequently属性以优化性能
  const ctx = canvas.getContext('2d', { willReadFrequently: true });
  
  // 创建自定义图层
  const customLayer = new AMap.CustomLayer(canvas, {
    zIndex: 16, // 提高zIndex确保在最上层
    zooms: [3, 20]
  });

  customLayer.render = function() {
    // 获取地图的中心点和缩放级别
    const center = map.getCenter();
    const zoom = map.getZoom();
    const bounds = map.getBounds();
    
    // 重置canvas尺寸
    canvas.width = map.getSize().width;
    canvas.height = map.getSize().height;
    
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制重庆市区域内的路网高亮效果
    ctx.strokeStyle = 'rgba(0, 255, 128, 1)'; // 调整为更亮的绿色
    ctx.lineWidth = 3; // 增加线宽
    ctx.shadowColor = 'rgba(0, 255, 128, 0.7)';
    ctx.shadowBlur = 6;
    
    // 要绘制的道路数据，根据实际情况可以调整
    // 此处简化处理，您可能需要使用真实的路网数据
    const mainRoads = [
      // 主城区域的主要道路
      { start: [106.5, 29.5], end: [106.7, 29.7] },
      { start: [106.3, 29.3], end: [106.6, 29.5] },
      { start: [106.4, 29.4], end: [106.8, 29.6] },
      { start: [106.2, 29.2], end: [106.5, 29.4] },
      { start: [106.6, 29.6], end: [106.9, 29.8] },
      // 添加更多覆盖重庆市主要区域的道路...
      { start: [107.0, 29.7], end: [107.3, 29.9] },
      { start: [106.8, 29.5], end: [107.1, 29.7] },
      { start: [106.7, 29.3], end: [107.0, 29.5] },
      { start: [106.9, 29.4], end: [107.2, 29.6] },
      { start: [107.1, 29.6], end: [107.4, 29.8] },
      // 东部区域
      { start: [107.5, 29.8], end: [107.8, 30.0] },
      { start: [107.3, 29.6], end: [107.6, 29.8] },
      { start: [107.4, 29.7], end: [107.7, 29.9] },
      // 西部区域
      { start: [106.0, 29.0], end: [106.3, 29.2] },
      { start: [105.8, 29.1], end: [106.1, 29.3] },
      { start: [106.1, 29.2], end: [106.4, 29.4] },
      // 南北连接
      { start: [106.5, 29.0], end: [106.5, 29.5] },
      { start: [106.7, 29.1], end: [106.7, 29.6] },
      { start: [106.9, 29.2], end: [106.9, 29.7] },
      { start: [107.1, 29.3], end: [107.1, 29.8] },
      // 添加更多路网线路
      { start: [106.4, 29.2], end: [106.4, 29.7] },
      { start: [106.6, 29.3], end: [106.6, 29.8] },
      { start: [106.8, 29.2], end: [106.8, 29.7] },
      { start: [107.0, 29.3], end: [107.0, 29.8] },
      { start: [106.2, 29.4], end: [106.7, 29.4] },
      { start: [106.3, 29.5], end: [106.8, 29.5] },
      { start: [106.4, 29.6], end: [106.9, 29.6] },
      { start: [106.3, 29.7], end: [106.8, 29.7] },
    ];
    
    // 绘制高亮路网
    mainRoads.forEach(road => {
      if (isInBoundaries(road.start, boundaries) || isInBoundaries(road.end, boundaries)) {
        const startPx = map.lngLatToContainer(new AMap.LngLat(road.start[0], road.start[1]));
        const endPx = map.lngLatToContainer(new AMap.LngLat(road.end[0], road.end[1]));
        
        ctx.beginPath();
        ctx.moveTo(startPx.x, startPx.y);
        ctx.lineTo(endPx.x, endPx.y);
        ctx.stroke();
      }
    });
  };
  
  // 添加自定义图层到地图
  customLayer.setMap(map);
  
  // 添加边界高亮效果
  const boundaryCanvas = document.createElement('canvas');
  const boundaryCtx = boundaryCanvas.getContext('2d', { willReadFrequently: true });
  
  const boundaryLayer = new AMap.CustomLayer(boundaryCanvas, {
    zIndex: 17,
    zooms: [3, 20]
  });
  
  boundaryLayer.render = function() {
    boundaryCanvas.width = map.getSize().width;
    boundaryCanvas.height = map.getSize().height;
    
    boundaryCtx.clearRect(0, 0, boundaryCanvas.width, boundaryCanvas.height);
    
    // 绘制边界高亮效果
    boundaries.forEach(boundary => {
      boundaryCtx.strokeStyle = 'rgba(66, 235, 255, 1)'; // 亮青色边界
      boundaryCtx.lineWidth = 3;
      boundaryCtx.shadowColor = 'rgba(66, 235, 255, 0.8)';
      boundaryCtx.shadowBlur = 8;
      
      boundaryCtx.beginPath();
      
      if (boundary.length > 0) {
        const startPx = map.lngLatToContainer(new AMap.LngLat(boundary[0].lng, boundary[0].lat));
        boundaryCtx.moveTo(startPx.x, startPx.y);
        
        for (let i = 1; i < boundary.length; i++) {
          const px = map.lngLatToContainer(new AMap.LngLat(boundary[i].lng, boundary[i].lat));
          boundaryCtx.lineTo(px.x, px.y);
        }
        
        boundaryCtx.closePath();
        boundaryCtx.stroke();
      }
    });
  };
  
  boundaryLayer.setMap(map);
}

// 判断点是否在边界内
function isInBoundaries(point, boundaries) {
  for (let i = 0; i < boundaries.length; i++) {
    const polygon = new AMap.Polygon({
      path: boundaries[i]
    });
    
    if (polygon.contains(new AMap.LngLat(point[0], point[1]))) {
      return true;
    }
  }
  return false;
}

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  if (map) {
    map.destroy();
    map = null;
  }
  // 移除window上的initMap引用
  if (window.initMap === initMap) {
    window.initMap = null;
  }
});
</script>

<style lang="scss" scoped>
.guardpost-view {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

#map-container {
  width: 100%;
  height: 100%;
  z-index: 1;
}

.title-container {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  color: #3ec6ff;
  font-size: 24px;
  font-weight: bold;
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.info-panel {
  position: absolute;
  top: 80px;
  right: 20px;
  width: 452px; // 调整宽度以适应GuardPointsPanel
  z-index: 10;
}

/* 自定义标记样式 */
:deep(.custom-marker) {
  position: relative;
  
  .marker-icon {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
  }
  
  .pulse-ring {
    position: absolute;
    top: -6px;
    left: -6px;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    animation: pulse 1.5s infinite;
  }
  
  &.online {
    .marker-icon {
      background-color: #00c853;
    }
    
    .pulse-ring {
      border: 2px solid rgba(0, 200, 83, 0.5);
    }
  }
  
  &.offline {
    .marker-icon {
      background-color: #ff5252;
    }
    
    .pulse-ring {
      display: none;
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 0.8;
  }
  70% {
    transform: scale(1.2);
    opacity: 0;
  }
  100% {
    transform: scale(0.8);
    opacity: 0;
  }
}
</style> 